<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/180x180a.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/32x32a.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/32x32a.png?v=5.1.4">


  <link rel="mask-icon" href="/images/180x180.svg?v=5.1.4" color="#222">


  <link rel="manifest" href="/images/manifest.json">




  <meta name="keywords" content="序列化,反序列化,">





  <link rel="alternate" href="/atom.xml" title="AbelChe's Blog" type="application/atom+xml">






<meta name="description" content="什么是序列化&amp;amp;反序列化 序列化: 序列化是将变量转换为可保存或传输的字符串的过程。  反序列化:将在序列化过程中所生成的字符串再转化成原来的变量使用。   PHP序列化的方法 PHP最初通过内置的serialize()和unserialize()函数来实现序列化。serialize()的参数可以是resource类型外的所有变量类型，最常见的是用来序列化对象，unseialize()将se">
<meta name="keywords" content="序列化,反序列化">
<meta property="og:type" content="article">
<meta property="og:title" content="序列化和反序列化">
<meta property="og:url" content="http://AbelChe.com/2018/11/01/序列化和反序列化/index.html">
<meta property="og:site_name" content="AbelChe&#39;s Blog">
<meta property="og:description" content="什么是序列化&amp;amp;反序列化 序列化: 序列化是将变量转换为可保存或传输的字符串的过程。  反序列化:将在序列化过程中所生成的字符串再转化成原来的变量使用。   PHP序列化的方法 PHP最初通过内置的serialize()和unserialize()函数来实现序列化。serialize()的参数可以是resource类型外的所有变量类型，最常见的是用来序列化对象，unseialize()将se">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://hnxkvw.sn.files.1drv.com/y4mwGUw-A2V2k_Uu5w-T-Ou8Z3YabDPIF42dF4POXVs1Hbyc8v6Ez65bYZm45qXY1XFPpQp_9H5RjldDUssJfjsRT0rKJh_XdlC21jmvVYuyQ9IVrOAG07dUK1y951w9KvSdKnJu7-bi8halyTaEz59Z7gvExnhYB9ueC-O0Gp9wjzbqm48YGQkvlJbahxxGxA_G6nnWC3YlJKZ-vJ4vTI59Q?width=1022&height=201&cropmode=none">
<meta property="og:image" content="https://hnxnvw.sn.files.1drv.com/y4mOCAkyMZKdYGn_dUWItGK-X1xd6zG1A6OVRPckNuSP2o3z6XQpizP9oJeCH-SqRfzXn_gEH5bRC9W-3tG1X6bszPqeByolKchltdhOF5Jdy0-fssKIf0lCuIsivVJBk5b9Hia7dQfa8sd4EDsNEOINzk7A6wP7iHmqNAn4l3yc9z8EuCZGUi2uBLroUG42s0fVepckc0Vn26y0nJpAeVw3Q?width=292&height=89&cropmode=none">
<meta property="og:image" content="https://hnxmvw.sn.files.1drv.com/y4mLO8sjjujtidnCGjcFM7nb8SOxswXTR_aeh2clsSCDT6rInjTXurhjKaAFk4rbizr277KZK56GNdO6m3QAGpGGVOLk1vCVcLar8UFCSN5wGQnpT0XR6pSwI29nqX7Byc4ffbYNoL0M9SkTp6jnmHMCinF7R0vGCh3Bd0tYxyaXsm0hmnSGU04LOylqWsXDBBLPuIkL08WNnFKd6SDdAhLSw?width=345&height=56&cropmode=none">
<meta property="og:image" content="https://hnxpvw.sn.files.1drv.com/y4mlAB2rR0Ly2OWnhfqw81vPjM3_N7Rplaz4pdwN3P-ZOjhYUqzyHEb7LYHa_WpEY6MugjTJlF5Sc6eKN8XOWEhoCgSu5aqweIoM7cYcOs-lNG1w3jtWSiQq9-cJ8-R4iIg2g0VD2UdiuiZUCsT1wUyuzW_-ksPd3VoEuHVD1SrGuPpbCI1LVDZlWhk1Ttv_bAIzTezKHze1mjYMu-GdcY1dA?width=935&height=124&cropmode=none">
<meta property="og:image" content="https://k9xnvw.sn.files.1drv.com/y4mA1SrTXYGLV_p2xj1l9ppGgrmV04wk5CzFXZKKS0bCBRpZ3bqOgx0MLzAh9CFDLE5iBpFNimEAYrmivr5CsAJ0BNPjc-7y9D2J40kZgEAlMm2PfkMlecvpqu4wrEkC9GrKDhIrZSUnSmdwvsMZ0Ni-zHR7xdZq1ybodjt2X5BSAqLXKITsplUTtC9mmDY8g36hJ6mH0eed88y35_G578GJg?width=935&height=687&cropmode=none">
<meta property="og:updated_time" content="2019-08-15T11:02:50.014Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="序列化和反序列化">
<meta name="twitter:description" content="什么是序列化&amp;amp;反序列化 序列化: 序列化是将变量转换为可保存或传输的字符串的过程。  反序列化:将在序列化过程中所生成的字符串再转化成原来的变量使用。   PHP序列化的方法 PHP最初通过内置的serialize()和unserialize()函数来实现序列化。serialize()的参数可以是resource类型外的所有变量类型，最常见的是用来序列化对象，unseialize()将se">
<meta name="twitter:image" content="https://hnxkvw.sn.files.1drv.com/y4mwGUw-A2V2k_Uu5w-T-Ou8Z3YabDPIF42dF4POXVs1Hbyc8v6Ez65bYZm45qXY1XFPpQp_9H5RjldDUssJfjsRT0rKJh_XdlC21jmvVYuyQ9IVrOAG07dUK1y951w9KvSdKnJu7-bi8halyTaEz59Z7gvExnhYB9ueC-O0Gp9wjzbqm48YGQkvlJbahxxGxA_G6nnWC3YlJKZ-vJ4vTI59Q?width=1022&height=201&cropmode=none">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"slideLeftIn","post_header":"fadeIn","post_body":"fadeIn","coll_header":"fadeIn","sidebar":"slideDownIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://AbelChe.com/2018/11/01/序列化和反序列化/">





  <title>序列化和反序列化 | AbelChe's Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta custom-logo">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">AbelChe's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">Youth means limitless possibilities.</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-在线运行">
          <a href="/runcode/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-code"></i> <br>
            
            在线运行
          </a>
        </li>
      
        
        <li class="menu-item menu-item-友链">
          <a href="/friends/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-at"></i> <br>
            
            友链
          </a>
        </li>
      
        
        <li class="menu-item menu-item-sitemap">
          <a href="/sitemap.xml" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br>
            
            站点地图
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>

<link rel="manifest" href="/manifest.json">

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://AbelChe.com/2018/11/01/序列化和反序列化/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="AbelChe">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/uploads/images/head.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="AbelChe's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">序列化和反序列化</h2>
        

        <div class="post-meta">
          
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-11-01T20:01:08+08:00">
                2018-11-01
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2019-08-15T19:02:50+08:00">
                2019-08-15
              </time>
            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2018/11/01/序列化和反序列化/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2018/11/01/序列化和反序列化/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i> 阅读数
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1,177 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  5 分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="什么是序列化-amp-反序列化"><a href="#什么是序列化-amp-反序列化" class="headerlink" title="什么是序列化&amp;反序列化"></a>什么是序列化&amp;反序列化</h1><ul>
<li><p>序列化: 序列化是将变量转换为可保存或传输的字符串的过程。</p>
</li>
<li><p>反序列化:将在序列化过程中所生成的字符串再转化成原来的变量使用。</p>
</li>
</ul>
<h1 id="PHP序列化的方法"><a href="#PHP序列化的方法" class="headerlink" title="PHP序列化的方法"></a>PHP序列化的方法</h1><blockquote>
<p>PHP最初通过内置的<code>serialize()</code>和<code>unserialize()</code>函数来实现序列化。<code>serialize()</code>的参数可以是<code>resource</code>类型外的所有变量类型，最常见的是用来序列化对象，<code>unseialize()</code>将<code>serialize</code>的返回结果作为参数，进行反序列化，得到原对象<br>对不受信任的数据上使用内置的<code>unserialize()</code>函数时，通常是有风险的。<br>对于对象有两种“魔术方法”，<code>__sleep()</code>和<code>__wakeup()</code>，可以在类别中实现。而会分别从<code>serialize()</code>和<code>unserialize()</code>中调用，对应于清理和恢复对象的功能。例如，在序列化时可能需要关闭数据库连线，并在反序列化时恢复连线；这个功能可在这两种魔术方法中处理。它们也允许对象选择哪些属性可被序列化。<br>从PHP 5.1开始有面向对象的序列化机制，即为<code>Serializable</code>接口。</p>
</blockquote>
<h1 id="PHP序列化的作用"><a href="#PHP序列化的作用" class="headerlink" title="PHP序列化的作用"></a>PHP序列化的作用</h1><h2 id="对象序列化使用情况"><a href="#对象序列化使用情况" class="headerlink" title="对象序列化使用情况:"></a>对象序列化使用情况:</h2><blockquote>
<ul>
<li>对象的创建的时候被存储到内存里，在解析的时候被销毁，如果机器重启，那么对象也将被销毁在新建。想要保存对象或者将对象传给另一台机器，就需要将对象序列化；或者在需要存储数据到mysql等数据库中时需要序列化。</li>
<li>将对象转化成字符串叫序列化</li>
<li>将字符串转化成对象叫反序列化</li>
</ul>
</blockquote>
<p><font size="4">总之，就是<strong><font color="red">方便数据传输</font></strong>和<strong><font color="red">存储</font></strong></font></p>
<br>
# 实例说明

<figure class="highlight clean"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">&lt;?php </span><br><span class="line">################建立一个数组###################</span><br><span class="line">$arr1 = [];</span><br><span class="line">for($i=<span class="number">0</span>; $i&lt;<span class="number">5</span>; $i++)</span><br><span class="line">	$arr1[<span class="string">'key'</span>.$i] = <span class="string">'value'</span>.$i;</span><br><span class="line">echo <span class="string">"建立一个数组arr1:"</span>;</span><br><span class="line">print_r($arr1);</span><br><span class="line">echo <span class="string">"&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;"</span>;</span><br><span class="line">##############################################</span><br><span class="line"></span><br><span class="line">################序列化该数组###################</span><br><span class="line">$arr_serialize = serialize($arr1);</span><br><span class="line">echo <span class="string">"arr1序列化后为:"</span>;</span><br><span class="line">print_r($arr_serialize);</span><br><span class="line">echo <span class="string">"&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;"</span>;</span><br><span class="line">##############################################</span><br><span class="line"></span><br><span class="line">###############反序列化后输出##################</span><br><span class="line">$arr_back = unserialize($arr_serialize);</span><br><span class="line">echo <span class="string">"arr_serialize反序列化后为:"</span>;</span><br><span class="line">print_r($arr_back);</span><br><span class="line">##############################################</span><br><span class="line">?&gt;</span><br></pre></td></tr></table></figure>

<p>输出结果如下<img src="https://hnxkvw.sn.files.1drv.com/y4mwGUw-A2V2k_Uu5w-T-Ou8Z3YabDPIF42dF4POXVs1Hbyc8v6Ez65bYZm45qXY1XFPpQp_9H5RjldDUssJfjsRT0rKJh_XdlC21jmvVYuyQ9IVrOAG07dUK1y951w9KvSdKnJu7-bi8halyTaEz59Z7gvExnhYB9ueC-O0Gp9wjzbqm48YGQkvlJbahxxGxA_G6nnWC3YlJKZ-vJ4vTI59Q?width=1022&height=201&cropmode=none" alt></p>
<p>注意这里序列化后的开头处是 <code>a</code> </p>
<p>再给出一段代码</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="php"><span class="meta">&lt;?php</span> </span></span><br><span class="line"><span class="php"><span class="class"><span class="keyword">class</span> <span class="title">test</span></span>&#123;			<span class="comment">#这里定义一个类</span></span></span><br><span class="line"><span class="php">	<span class="keyword">var</span> $value = <span class="string">'abc123'</span>;</span></span><br><span class="line"><span class="php">&#125;</span></span><br><span class="line"></span><br><span class="line"><span class="php">$obj = <span class="keyword">new</span> test;	<span class="comment">#new一个对象obj出来</span></span></span><br><span class="line"><span class="php">$obj_serialize = serialize($obj); <span class="comment">#将obj序列化</span></span></span><br><span class="line"><span class="php">print_r($obj_serialize);</span></span><br><span class="line"><span class="php"><span class="keyword">echo</span> <span class="string">"&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;"</span>;</span></span><br><span class="line"><span class="php">$obj_back = unserialize($obj_serialize); <span class="comment">#反序列化obj_serialize</span></span></span><br><span class="line"><span class="php">print_r($obj_back);</span></span><br><span class="line"><span class="php"> <span class="meta">?&gt;</span></span></span><br></pre></td></tr></table></figure>

<p>输出结果为:<img src="https://hnxnvw.sn.files.1drv.com/y4mOCAkyMZKdYGn_dUWItGK-X1xd6zG1A6OVRPckNuSP2o3z6XQpizP9oJeCH-SqRfzXn_gEH5bRC9W-3tG1X6bszPqeByolKchltdhOF5Jdy0-fssKIf0lCuIsivVJBk5b9Hia7dQfa8sd4EDsNEOINzk7A6wP7iHmqNAn4l3yc9z8EuCZGUi2uBLroUG42s0fVepckc0Vn26y0nJpAeVw3Q?width=292&height=89&cropmode=none" alt></p>
<ul>
<li>发现不同之处</li>
<li>当一个数组序列化时，以<code>a</code> 为标志，对象序列化是以 <code>O</code> 为标志</li>
<li>由此可以解读 PHP 序列化:<blockquote>
<p>a 代表的是 array 数组，5代表变量名称有几个字符， s 代表 string字符串类型，4 为 几个字符，后面的是字符串本身……<br>O 代表 object 对象；4代表的是序列化的对象名称有几个字符；对象名称；1为对象有一个值……</p>
</blockquote>
</li>
</ul>
<h1 id="unserialize-反序列化函数漏洞"><a href="#unserialize-反序列化函数漏洞" class="headerlink" title="unserialize()反序列化函数漏洞"></a>unserialize()反序列化函数漏洞</h1><blockquote>
<p>有前面的铺垫，我们可知道序列化得到的字符串是可解读的，那么如果精心构造一个字符串传给unserialize()进行反序列化，就可以控制到我们想控制的东西</p>
</blockquote>
<ul>
<li><p>前面提到过，当 PHP 调用<code>serizlize()</code>和<code>unserialize()</code>函数时，会调用<code>__sleep()</code>和<code>__wakeup()</code>两个魔术方法(Magic function)</p>
</li>
<li><p>先介绍下魔术方法:</p>
</li>
</ul>
<h2 id="魔术方法-Magic-function"><a href="#魔术方法-Magic-function" class="headerlink" title="魔术方法(Magic function)"></a>魔术方法(Magic function)</h2><p>在命名自己的类方法时不能使用这些方法名，除非是想用其魔术功能。<br><a href="https://secure.php.net/manual/zh/language.oop5.magic.php" target="_blank" rel="noopener">PHP官方文档-魔术方法</a><br><a href="http://www.php.cn/php-weizijiaocheng-406955.html" target="_blank" rel="noopener">PHP中文网-魔术方法</a></p>
<p>利用反序列化漏洞</p>
<h2 id="unserialize-调用-wakeup-魔术方法"><a href="#unserialize-调用-wakeup-魔术方法" class="headerlink" title="unserialize()调用__wakeup()魔术方法"></a><code>unserialize()</code>调用<code>__wakeup()</code>魔术方法</h2><ul>
<li><p>一个例子:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="php"><span class="meta">&lt;?php</span> </span></span><br><span class="line"><span class="php"><span class="class"><span class="keyword">class</span> <span class="title">test</span></span>&#123;			<span class="comment">#这里定义一个类</span></span></span><br><span class="line"><span class="php">	<span class="keyword">var</span> $value = <span class="string">'abc123'</span>;</span></span><br><span class="line"><span class="php">	<span class="function"><span class="keyword">function</span> <span class="title">__wakeup</span><span class="params">()</span></span>&#123;</span></span><br><span class="line"><span class="php">		<span class="keyword">echo</span> <span class="string">"__wakeup&lt;/br&gt;"</span>;</span></span><br><span class="line"><span class="php">	&#125;</span></span><br><span class="line"><span class="php">&#125;</span></span><br><span class="line"></span><br><span class="line"><span class="php">$demo = unserialize(<span class="string">'O:4:"test":1:&#123;s:5:"value";s:6:"abc123";&#125;'</span>);</span></span><br><span class="line"><span class="php"><span class="comment">#O:4:"test":1:&#123;s:5:"value";s:6:"abc123";&#125;是序列化test-&gt;value的值</span></span></span><br><span class="line"><span class="php">print_r($demo);</span></span><br><span class="line"><span class="php"> <span class="meta">?&gt;</span></span></span><br></pre></td></tr></table></figure>
</li>
<li><p>结果如下:<br>明显<code>unserialize()</code>调用了<code>__wakeup()</code><br><img src="https://hnxmvw.sn.files.1drv.com/y4mLO8sjjujtidnCGjcFM7nb8SOxswXTR_aeh2clsSCDT6rInjTXurhjKaAFk4rbizr277KZK56GNdO6m3QAGpGGVOLk1vCVcLar8UFCSN5wGQnpT0XR6pSwI29nqX7Byc4ffbYNoL0M9SkTp6jnmHMCinF7R0vGCh3Bd0tYxyaXsm0hmnSGU04LOylqWsXDBBLPuIkL08WNnFKd6SDdAhLSw?width=345&height=56&cropmode=none" alt></p>
</li>
</ul>
<h2 id="利用unserialize-函数漏洞"><a href="#利用unserialize-函数漏洞" class="headerlink" title="利用unserialize()函数漏洞"></a>利用unserialize()函数漏洞</h2><ul>
<li>环境:</li>
<li>index.php和shell.php</li>
</ul>
<p>index.php</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="php"><span class="meta">&lt;?php</span></span></span><br><span class="line"><span class="php"><span class="class"><span class="keyword">class</span> <span class="title">test</span></span>&#123;</span></span><br><span class="line"><span class="php">	<span class="keyword">var</span> $value = <span class="string">'123'</span>;</span></span><br><span class="line"><span class="php">	<span class="function"><span class="keyword">function</span> <span class="title">__wakeup</span><span class="params">()</span></span>&#123;</span></span><br><span class="line"><span class="php">		$fp = fopen(<span class="string">"shell.php"</span>,<span class="string">"w"</span>) ;</span></span><br><span class="line"><span class="php">		fwrite($fp,<span class="keyword">$this</span>-&gt;value);</span></span><br><span class="line"><span class="php">		fclose($fp);</span></span><br><span class="line"><span class="php">	&#125;</span></span><br><span class="line"><span class="php">&#125;</span></span><br><span class="line"><span class="php">$get = $_GET[<span class="string">'getvalue'</span>];</span></span><br><span class="line"><span class="php">unserialize($get);</span></span><br><span class="line"></span><br><span class="line"><span class="php"><span class="meta">?&gt;</span></span></span><br></pre></td></tr></table></figure>

<ul>
<li>我们可以控制序列化的字符串达到利用<code>__wakeup()</code>函数的目的</li>
<li>这里构造一个包含有<code>phpinfo();</code>的字符串</li>
</ul>
<p>PHP脚本如下:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="php"><span class="meta">&lt;?php</span> </span></span><br><span class="line"><span class="php"><span class="class"><span class="keyword">class</span> <span class="title">test</span></span>&#123;</span></span><br><span class="line"><span class="php">	<span class="keyword">var</span> $value = <span class="string">'123'</span>;</span></span><br><span class="line"><span class="php">&#125;</span></span><br><span class="line"><span class="php">$obj = <span class="keyword">new</span> test;</span></span><br><span class="line"><span class="php">$obj-&gt;value = <span class="string">"&lt;?php phpinfo(); ?&gt;"</span>;</span></span><br><span class="line"><span class="php">$temp = serialize($obj);</span></span><br><span class="line"><span class="php">print_r($temp);</span></span><br><span class="line"><span class="php"> <span class="meta">?&gt;</span></span></span><br></pre></td></tr></table></figure>

<p>运行后得到<br><code>O:4:&quot;test&quot;:1:{s:5:&quot;value&quot;;s:19:&quot;&lt;?php phpinfo(); ?&gt;&quot;;}</code></p>
<p>将其传入漏洞站点<br><img src="https://hnxpvw.sn.files.1drv.com/y4mlAB2rR0Ly2OWnhfqw81vPjM3_N7Rplaz4pdwN3P-ZOjhYUqzyHEb7LYHa_WpEY6MugjTJlF5Sc6eKN8XOWEhoCgSu5aqweIoM7cYcOs-lNG1w3jtWSiQq9-cJ8-R4iIg2g0VD2UdiuiZUCsT1wUyuzW_-ksPd3VoEuHVD1SrGuPpbCI1LVDZlWhk1Ttv_bAIzTezKHze1mjYMu-GdcY1dA?width=935&height=124&cropmode=none" alt></p>
<p>打开shell.php发现成功写入<code>&lt;?php phpinfo(); ?&gt;</code> 并解析成功<br><img src="https://k9xnvw.sn.files.1drv.com/y4mA1SrTXYGLV_p2xj1l9ppGgrmV04wk5CzFXZKKS0bCBRpZ3bqOgx0MLzAh9CFDLE5iBpFNimEAYrmivr5CsAJ0BNPjc-7y9D2J40kZgEAlMm2PfkMlecvpqu4wrEkC9GrKDhIrZSUnSmdwvsMZ0Ni-zHR7xdZq1ybodjt2X5BSAqLXKITsplUTtC9mmDY8g36hJ6mH0eed88y35_G578GJg?width=935&height=687&cropmode=none" alt></p>
<hr>

      
    </div>
    
    
    

    
      <div>
        <div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/uploads/images/wechatQR_2.JPG" alt="AbelChe wechat" style="width: 200px; max-width: 100%;">
    <div>扫码加微信</div>
</div>

      </div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>Donate here!!!</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="AbelChe 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="AbelChe 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    AbelChe
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://AbelChe.com/2018/11/01/序列化和反序列化/" title="序列化和反序列化">http://AbelChe.com/2018/11/01/序列化和反序列化/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/序列化/" rel="tag"># 序列化</a>
          
            <a href="/tags/反序列化/" rel="tag"># 反序列化</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/10/31/使用shadowsocks(R)-搭建vpn服务/" rel="next" title="使用shadowsocks(R)搭建vpn服务">
                <i class="fa fa-chevron-left"></i> 使用shadowsocks(R)搭建vpn服务
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/11/16/Centos7-搭建-l2tp-vpn/" rel="prev" title="Centos7 搭建 l2tp vpn">
                Centos7 搭建 l2tp vpn <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <a href="/"><img class="site-author-image" itemprop="image" src="/uploads/images/head.png" alt="AbelChe"></a>
            
              <a href="/"><p class="site-author-name" itemprop="name">AbelChe</p></a>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">65</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">81</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/AbelChe" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://coding.net/u/AbelChe" target="_blank" title="Coding">
                      
                        <i class="fa fa-fw fa-bullseye"></i>Coding</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/abelche" target="_blank" title="Gitee">
                      
                        <i class="fa fa-fw fa-codepen"></i>Gitee</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.aliyun.com" target="_blank" title="Aliyun">
                      
                        <i class="fa fa-fw fa-cloud"></i>Aliyun</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://mail.qq.com" target="_blank" title="QQ_mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>QQ_mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="http://mail.google.com/mail/" target="_blank" title="Gmail">
                      
                        <i class="fa fa-fw fa-google"></i>Gmail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://twitter.com/AbelChe7" target="_blank" title="Twitter">
                      
                        <i class="fa fa-fw fa-twitter"></i>Twitter</a>
                  </span>
                
            </div>
          

          
          
            <div class="cc-license motion-element" itemprop="license">
              <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank">
                <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons">
              </a>
            </div>
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                LINKS
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.baidu.com" title="Baidu" target="_blank">Baidu</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.google.com" title="Google" target="_blank">Google</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.csdn.net" title="CSDN" target="_blank">CSDN</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.bilibili.com" title="Bilibili" target="_blank">Bilibili</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.taobao.com" title="Taobao" target="_blank">Taobao</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000" title="Python Learning" target="_blank">Python Learning</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#什么是序列化-amp-反序列化"><span class="nav-number">1.</span> <span class="nav-text">什么是序列化&amp;反序列化</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#PHP序列化的方法"><span class="nav-number">2.</span> <span class="nav-text">PHP序列化的方法</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#PHP序列化的作用"><span class="nav-number">3.</span> <span class="nav-text">PHP序列化的作用</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#对象序列化使用情况"><span class="nav-number">3.1.</span> <span class="nav-text">对象序列化使用情况:</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#unserialize-反序列化函数漏洞"><span class="nav-number">4.</span> <span class="nav-text">unserialize()反序列化函数漏洞</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#魔术方法-Magic-function"><span class="nav-number">4.1.</span> <span class="nav-text">魔术方法(Magic function)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#unserialize-调用-wakeup-魔术方法"><span class="nav-number">4.2.</span> <span class="nav-text">unserialize()调用__wakeup()魔术方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#利用unserialize-函数漏洞"><span class="nav-number">4.3.</span> <span class="nav-text">利用unserialize()函数漏洞</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">AbelChe</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">43.8k</span>
  
</div>


<!--
  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>
-->








        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i> 访问人数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i> 总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: '3dNwvfMcT2yQEr3TkP1gFUbT-gzGzoHsz',
        appKey: 'bjkjOibLdLJcGGrHkTXWeXpA',
        placeholder: 'Just go go',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
    
      flOptions = {};
      
          flOptions.iconStyle = "box";
      
          flOptions.boxForm = "horizontal";
      
          flOptions.position = "middleRight";
      
          flOptions.networks = "Weibo,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>

  

  

  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.4"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.4"></script>


  
  <script type="text/javascript" src="/js/src/exturl.js?v=5.1.4"></script>


</body>
</html>
